// pages/cashier_pay/cashier_pay.js
// var WxParse = require('../../../wxParse/wxParse.js');
var yz_pay = require("../../../mycomponent/yz_pay/yz_pay");
var app = getApp();
Page({
  behaviors: [yz_pay],
  /**
   * 页面的初始数据
   */
  data: {
    language: "",
    //是否显示支付协议
    agreementPayData: "",
    agreementPay: false,
    agreementPayShow: false,
    store_id: "",
    confirmOrderStatus: false,
    payMuch: "0",
    realname: "", //收件人
    mobile: "",
    //优惠券
    popupCouponSpecs: false,
    checkCouponList: [],
    coupon_size: 0,
    use_coupon_size: 0,
    coupons: [],
    cup_notice: true,
    isShowCoupon: false, //是否显示优惠券
    //支付
    order_ids: "",
    income: {
      money_total: 0.0,
      sure_withdraw_money: 0.0,
    },
    store_set: {
      is_cash_pay: "",
      is_open_cashier: "",
      is_write_information: "",
    },
    payPrice: 0,
    //积分抵扣 其他抵扣
    checkDeductionList: [],
    form: {
      mobile: "",
      realname: "",
    },
    allData: {},
    order_data: "",
    loadDiscount: false,
    goods_price: 0.0,
    dispatch_price: 0.0,
    discount_price: 0,
    price: 0.0,
    deduction_price: 0,
    payType: [],
    typename: "",
    show1: false,
    clicktag: 0,
    uid: "",
    cashier_type: "",
    hotel_id: "",
    order_pay_id: "",

    //消费红包
    showPacket: false,
    redirectData: {},
    balanceNow_store:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var info_arr = [];
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      console.log(scene);
      if (scene) {
        info_arr = scene.split(",");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          console.log(chil_arr);
          if (chil_arr[0] == "store_id") {
            this.setData({
              store_id: chil_arr[1],
            });
          }
          if (chil_arr[0] == "hotel_id") {
            this.setData({
              hotel_id: chil_arr[1],
            });
          }
          if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
          }
        }
      }
    }
    if (options.q) {
      let qscen = decodeURIComponent(options.q);
      console.log(qscen);
      if (qscen) {
        let scene = decodeURIComponent(options.q);
        if (scene) {
          
          if (scene.indexOf("?i=") == "-1") {
            info_arr = scene.split(",");
          } else {
            let arr = scene.split("&");
            info_arr = arr[1].split(",");
          }
          for (let i = 0; i < info_arr.length; i++) {
            let chil_arr = [];
            chil_arr = info_arr[i].split("=");
            if (chil_arr[1] == "store_id") {
              this.setData({
                store_id: chil_arr[2],
              });
            }
            if (chil_arr[0] == "mid") {
              app._setMid(chil_arr[1]);
            }
          }
        }
      }
    }
    if (options.hotel_id) {
      this.setData({
        hotel_id: options.hotel_id,
      });
    }
    if (app._isTextEmpty(this.data.hotel_id)) {
      this.setData({
        cashier_type: "store",
      });
    } else {
      this.setData({
        cashier_type: "hotel",
      });
    }
    if (options.store_id) {
      this.setData({
        store_id: options.store_id,
      });
    }
    if(options.cashier_type){
      this.setData({
        cashier_type:options.cashier_type
      });
    }
    if(this.data.cashier_type == "scanning_payment"){
      this.setData({
        payMuch:options.price,
        show1:true,
        showPage:true
      });
      wx.setNavigationBarTitle({
        title: '扫码下单',
      });
      this.preGoodsBuy();
    }else {
      this.getCenter();
    }
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({
      language: language.en,
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let _url = '/packageC/cashier/cashier_pay/cashier_pay'
    if(this.data.store_id) _url = `${_url}?store_id=${this.data.store_id}`
    if(this.data.hotel_id) _url = `${_url}?hotel_id=${this.data.hotel_id}`
    return{
      path: _url
    };
  },
  fromChild(e){
    if(this.data.money=='0.00'|| e.detail.money == '0.00') {
      // 0元
      // this.sureBtn();
      this.submit('54')
    }else {
      let datas = e.detail.submitArr;
      this.submit(datas);
    }
  },
  onClickHide() {
    this.setData({
      showPacket: false,
    });
    this.toRedirect();
  },
  toPacket() {
    wx.redirectTo({
      url: "/packageE/ConsumePacket/ConsumePacketSuccess/ConsumePacketSuccess?order_id=" + this.data.order_ids.toString(),
    });
  },
  // 消费红包
  checkoutConsumePacket() {
    this.getVoiceSet();
    let basicinfo = wx.getStorageSync("yz_basic_info");
    if (basicinfo && basicinfo.globalParameter.consume_red_packet_status == 1) {
      let urlStr = app.getNetAddresss("plugin.consume-red-packet.Frontend.Modules.Packet.Controllers.has.index");
      app._postNetWork({
        url: urlStr,
        data: {
          order_id: this.data.order_ids.split(","),
        },
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            this.setData({
              show1: false,
              showPacket: true,
            });
          } else {
            this.toRedirect();
          }
        },
        fail: (res) => {
          this.toRedirect();
          console.log(res);
        },
      });
    } else {
      this.toRedirect();
    }
  },
  toRedirect() {
    wx.showToast({
      icon: "none",
      title: "支付成功",
      duration: 2000,
    });
    if (this.data.order_sn) {
      this.payCallBack();
    }
    // wx.showModal({
    //   title: "提示",
    //   content: "支付成功",
    //   showCancel: false,
    //   success: (res) => {
    //     if (res.confirm) {
    //       if (this.data.redirectData.cashPay) {
    //         wx.reLaunch({
    //           url: "/packageG/member_v2/member_v2",
    //         });
    //       } else if (!app._isTextEmpty(this.data.min_redirect_url)) {
    //         try {
    //           wx.redirectTo({
    //             url: this.data.min_redirect_url,
    //           });
    //         } catch (e) {
    //           console.log(e);
    //         }
    //       } else {
    //         wx.reLaunch({
    //           url: "/packageG/index/index",
    //         });
    //       }
    //     }
    //   },
    // });
  },
  getVoiceSet() {
    //判断是否开启语音播报
    // let that = this;
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.cashier.voice.index");
    app._postNetWork({
      url: urlStr,
      data: {
        order_id: this.data.order_ids,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          // const bgMusic = wx.createInnerAudioContext();
          const bgMusic = wx.getBackgroundAudioManager(); //音乐播放实例
          // //bug ios 播放时必须加title 不然会报错导致音乐不播放
          bgMusic.title = "支付成功语音提示";
          bgMusic.src = res.data.url;
          bgMusic.play();
          // bgMusic.src = `data:audio/x-wav;base64,${res.data.speech}`;
          // bgMusic.src = 'https://dev4.yunzmall.com/attachment/audios/0/2021/05/556f15b68d5d2c1886e2e470e6f1cda9.mp3'
        } else {
          console.log(res);
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  PayShowbtn() {
    this.setData({
      agreementPayShow: false,
    });
  },
  initStore(data) {
    this.setData({
      confirmOrderStatus: false,
      payMuch: "0",
      realname: "",
      mobile: "",
      popupCouponSpecs: false,
      order_ids: "",
    });
    if (this.data.cashier_type === "hotel") {
      // 酒店没有用到，这是用来统计门店订单的 任务编号: 54992
      // this.setData({
      // 	store: data.hotel,
      // 	store_set: data.hotel_set
      // })
    } else {
      this.setData({
        store: data.store,
        store_set: data.store_set,
        income: data.income,
      });
      if(Number(data.store_set.every_min_money)){
        // perf#2473 门店收银台最低消费
        this.setData({
          payMuch:data.store_set.every_min_money
        })
      }
      if(data.store_set.is_open_cashier != 1) {
        // 该门店没有开启收银台
        app.confirm('该门店没有开启收银台',()=> {
          wx.navigateBack({
            delta: 1,
            fail: ()=> {
              wx.reLaunch({
                url: '/packageG/index/index',
              });
            }
          });
        },false);
      }
    }
  },
  //处理按键
  _handleKeyPress(e) {
    let num = e.currentTarget.dataset.num;
    //不同按键处理逻辑
    // -1 代表无效按键，直接返回
    if (num == -1) return false;
    switch (String(num)) {
    //小数点
    case ".":
      this._handleDecimalPoint();
      break;
    //删除键
    case "D":
      this._handleDeleteKey();
      break;
    //确认键
    case "S":
      this._handleConfirmKey();
      break;
    default:
      this._handleNumberKey(num);
      break;
    }
  },
  //处理小数点函数
  _handleDecimalPoint() {
    //如果包含小数点，直接返回
    if (this.data.payMuch.indexOf(".") > -1) {
      return false;
    }
    //如果小数点是第一位，补0
    if (!this.data.payMuch.length) {
      this.setData({
        payMuch: "0.",
      });
    } else {
      //如果不是，添加一个小数点
      this.setData({
        payMuch: this.data.payMuch + ".",
      });
    }
  },
  //处理删除键
  _handleDeleteKey() {
    let S = this.data.payMuch;
    //如果没有输入，直接返回
    if (S.length <= 1) {
      this.setData({
        payMuch: "0",
      });
      return;
    }
    //否则删除最后一个
    this.setData({
      payMuch: S.substring(0, S.length - 1),
    });
  },
  _handleConfirmKey() {
    let S = this.data.payMuch;
    //未输入
    if (!S.length || Number(S) === 0) {
      wx.showToast({
        icon: "none",
        title: "您目前未输入!",
        duration: 1500,
      });
      return false;
    }
    //将 8. 这种转换成 8.00
    if (S.indexOf(".") > -1 && S.indexOf(".") === S.length - 1) {
      S = Number(S.substring(0, S.length - 1)).toFixed(2);
    }
    //保留两位
    S = Number(S).toFixed(2);
    this.setData({
      payMuch: S,
    });
    this.confirmOrder();
  },
  confirmOrder() {
    var val = this.data.payMuch;
    if (val && val > 0) {
      this.setData({
        payPrice: val,
        confirmOrderStatus: true,
        isdisabled: true,
      });
      this.preGoodsBuy();
    } else {
      wx.showToast({
        icon: "none",
        title: "请输入正确的付款金额!",
        duration: 1500,
      });
      this.setData({
        confirmOrderStatus: false,
        isdisabled: false,
      });
    }
  },
  //处理数字
  _handleNumberKey(num) {
    let S = this.data.payMuch;
    //如果有小数点且小数点位数不小于2
    if (S.indexOf(".") > -1 && S.substring(S.indexOf(".") + 1).length < 2) {
      this.setData({
        payMuch: S + num,
      });
    }
    //没有小数点
    if (!(S.indexOf(".") > -1)) {
      //如果第一位是0，只能输入小数点
      if (num == 0 && S.length == 0) {
        this.setData({
          payMuch: "0.",
        });
      } else {
        if (S.length && Number(S.charAt(0)) === 0) {
          this.setData({
            payMuch: num,
          });
          return;
        }
        this.setData({
          payMuch: S + num,
        });
      }
    }
  },
  //直接购买
  preGoodsBuy() {
    let that = this;
    let urlStr = "";
    if (this.data.cashier_type == "hotel") {
      urlStr += app.getNetAddresss("plugin.hotel.frontend.Order.goods-buy");
      urlStr += "&price=" + this.data.payPrice;
      urlStr += "&hotel_id=" + this.data.hotel_id;
      urlStr += "&member_coupon_ids=" + this.assembleCoupons();
      urlStr += "&orders=" + JSON.stringify(this.assembleDeduction());
      urlStr += "&mobile=" + this.data.form.mobile;
      urlStr += "&realname=" + this.data.form.realname;
    } else if(this.data.cashier_type == "scanning_payment"){
      urlStr += app.getNetAddresss("plugin.sweep-buy.frontend.controllers.goods-buy.index");
      urlStr += "&member_coupon_ids=" + this.assembleCoupons();
      urlStr += "&price=" + this.data.payMuch;
      urlStr += "&goods_id=" + this.options.goods_id;
      urlStr += "&orders=" + JSON.stringify(this.assembleDeduction());
    }else {
      urlStr += app.getNetAddresss("plugin.store-cashier.frontend.Order.goods-buy");
      urlStr += "&price=" + this.data.payPrice;
      urlStr += "&store_id=" + this.data.store_id;
      urlStr += "&member_coupon_ids=" + this.assembleCoupons();
      urlStr += "&orders=" + JSON.stringify(this.assembleDeduction());
      urlStr += "&mobile=" + this.data.form.mobile;
      urlStr += "&realname=" + this.data.form.realname;
    }
    if (this.data.clicktag == 0) {
      this.setData({
        clicktag: 1,
      });
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            if(res.data.balance){
              that.setData({
                balanceNow:res.data.balance
              });
            }
            if(that.data.cashier_type == 'store'){
              if(res.data.store_balance){
                that.setData({
                  balanceNow_store:res.data.store_balance
                })
              }
            }
            that.setViewData(res.data); //设置界面
            // if (that.data.cashier_type != "hotel") {
            that.initCoupon(res.data.discount); //设置优惠券信息
            // }
            that.initPayType();
          } else {
            wx.showModal({
              title: "提示",
              content: res.msg,
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  wx.navigateBack({
                    delta: 1,
                  });
                }
              },
            });
          }
          setTimeout(function () {
            that.setData({
              clicktag: 0,
            });
          }, 1000);
        },
        fail: function (res) {
          console.log(res);
        },
      });
    }
  },
  //组装优惠券json信息
  assembleCoupons() {
    let coupons = [];
    for (let i = 0; i < this.data.checkCouponList.length; i++) {
      if (this.data.is_coupon_SELE) {
        //开启折叠优惠券
        let conpon_arr = this.data.checkCouponList[i].has_conpon_id;
        // console.log("............", this.data.coupons_temp[this.data.checkCouponList[i].coupon_id].num);
        coupons = coupons.concat(conpon_arr.slice(0, this.data.coupons_temp[this.data.checkCouponList[i].coupon_id].num));
        this.setData({
          use_coupon_size: coupons.length,
        });
      } else {
        coupons.push(this.data.checkCouponList[i].id);
      }
    }
    return coupons;
  },
  //组装优惠抵扣信息
  assembleDeduction() {
    let deductions = [];
    for (let i = 0; i < this.data.checkDeductionList.length; i++) {
      deductions.push(this.data.checkDeductionList[i]);
    }
    return deductions;
  },
  //设置界面
  setViewData(data) {
    // console.log(data.orders, '55454');
    this.setData({
      allData: data,
      order_data: data.orders,
      loadDiscount: true,
      goods_price: data.total_goods_price, //设置商品总价格
      dispatch_price: data.total_dispatch_price, //设置总运费价格
      deduction_price: data.total_deduction_price, //设置总抵扣价格
      price: data.total_price, //设置总价格（合计）
      // 服务费
      service: data.orders[0].order_fees,
      datas: data.orders[0],
    });
    if (this.data.cashier_type != "hotel") {
      this.setData({
        discount_price: data.total_discount_price, //设置总优惠价格
      });
    }
  },
  //初始化优惠券
  initCoupon(data) {
    if (data.deduction_lang) {
      this.setData({
        deduction_lang: data.deduction_lang
      });
    }
    this.setData({
      isShowCoupon: data.whether_show_coupon == "1" ? true : false,
    });
    let coupon = data.member_coupons;
    this.setData({
      is_coupon_SELE: data.coupon_show == "1" ? true : false,
    });
    this.setData({
      coupon_size: coupon.length,
    });
    if (coupon != undefined && coupon != "" && coupon != null) {
      if (this.data.is_coupon_SELE) {
        //按过期时间排序
        let arr2 = coupon.sort((a, b) => {
          return a.expired_at - b.expired_at;
        });
        this.initSelectCoupon(arr2);
      } else {
        this.setData({
          coupons: coupon,
        });
      }
    }
  },
  //初始化带有默认选中优惠券
  defaultSelectCoupon(coupon) {
    let checkCouponList = [];
    coupon.forEach((item, ind) => {
      if (item.checked == true) {
        checkCouponList.push(item);
      }
    });
    this.setData({
      coupon_size: coupon.length,
      coupons: coupon,
      use_coupon_size: checkCouponList.length,
      checkCouponList: checkCouponList,
    });
    console.log(this.data.coupons);
  },
  //折叠优惠券
  initSelectCoupon(coupon) {
    let coupon_data = coupon;
    let result = [];
    let temp = {};

    for (let i = 0; i < coupon_data.length; i++) {
      let num = 0; //同类型已选中并符合使用条件的优惠券数量
      let valid = 0; //最高限制使用数量
      let has_conpon_id = [coupon_data[i].id];
      if (coupon_data[i].checked) {
        num++;
      }
      if (coupon_data[i].valid) {
        valid++;
      }
      for (let j = i + 1; j < coupon_data.length; j++) {
        if (coupon_data[i].coupon_id == coupon_data[j].coupon_id) {
          if (coupon_data[j].checked) {
            num++;
          }
          if (coupon_data[j].valid) {
            valid++;
          }
          has_conpon_id.push(coupon_data[j].id);
          coupon_data.splice(j, 1);
          j--;
        }
      }
      let _data = coupon_data[i];
      _data.has_conpon_id = has_conpon_id;
      _data.valid_num = valid;
      result.push(_data);
      temp[coupon_data[i].coupon_id] = {};
      temp[coupon_data[i].coupon_id].num = num;
    }
    this.setData({
      coupons_temp: temp,
      coupons: result,
    });
    console.log(this.data.coupons, this.data.coupons_temp);
  },
  changeConpon(e) {
    let valObj = e.target.dataset.item;
    let num = e.detail;
    let index = e.target.dataset.index;
    if (num > valObj.valid_num) {
      wx.showToast({
        icon: "none",
        title: "使用张数已达上限",
        duration: 1000,
      });
      clearTimeout(this.data.timer);
      this.data.timer = setTimeout(() => {
        // 注意此时修改 value 后会再次触发 change 事件
        this.data.coupons_temp[valObj.coupon_id].num = valObj.valid_num;
        this.setData({
          coupons_temp: this.data.coupons_temp,
        });
      }, 200);
      return;
    } else if (num == "" || num == undefined || num == 0) {
      wx.showToast({
        icon: "none",
        title: "暂不使用请取消勾选",
        duration: 1000,
      });
      return;
    } else {
      clearTimeout(this.data.timer);
      this.data.coupons_temp[valObj.coupon_id].num = num;
      this.setData({
        coupons_temp: this.data.coupons_temp,
      });
    }

    // clearTimeout方法，以便控制连续触发带来的无用调用
    let value = {
      detail: true,
      currentTarget: {
        dataset: {
          index: index,
          item: valObj,
        },
      },
    };
    if (this.data.timeoutId) {
      clearTimeout(this.data.timeoutId); // 先清除之前的延时，并在下面重新开始计算时间
    }
    this.data.timeoutId = setTimeout(() => {
      // 100毫秒以后执行方法
      this.selectCoupon(value);
    }, 1000); // 如果还没有执行就又被触发，会根据上面的clearTimeout来清除并重新开始计算
  },
  initPayType() {
    let that = this;
    let urlStr = "";
    if (this.data.cashier_type === "hotel") {
      urlStr += app.getNetAddresss("plugin.hotel.frontend.payment.list");
      urlStr += "&hotel_id=" + this.data.hotel_id;
      urlStr += "&price=" + this.data.payMuch;
    } else if(this.data.cashier_type == "scanning_payment"){
      urlStr += app.getNetAddresss("plugin.sweep-buy.frontend.controllers.payment.list");
      urlStr += "&price=" + this.data.payMuch;
    } else {
      urlStr += app.getNetAddresss("plugin.store-cashier.frontend.payment.list");
      urlStr += "&store_id=" + this.data.store_id;
      urlStr += "&price=" + this.data.payMuch;
    }
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let payTypeData = res.data;
          let arr = {};
          arr.buttons = res.data;
          that.hanleIcon(arr);
          that.setData({
            payType: payTypeData,
            typename: "支付",
            show1: true,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
            success: function () {
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1,
                });
              }, 1500); //延迟时间
            },
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  btnstyle(type) {
    if (type == 1 || type == 6 || type == 9 || type == 12 || type == 20 || type == 22) {
      return "#64b42e";
    } else if (type == 2 || type == 7 || type == 10 || type == 15 || type == 21) {
      return "#069ce7";
    } else if (type == 3) {
      return "#fc992c";
    } else if (type == 14) {
      return "#e36724";
    } else if (type == 18) {
      return "#dedede";
    } else {
      return "#fac337";
    }
  },
  btnclass(type) {
    if (type == 1 || type == 6 || type == 9 || type == 12 || type == 20 || type == 22) {
      return "icon-pay_b";
    } else if (type == 2 || type == 7 || type == 10 || type == 15 || type == 21) {
      return "icon-pay_c";
    } else if (type == 3) {
      return "icon-pay_d";
    } else if (type == 14) {
      return "icon-pay_f";
    } else if (type == 18) {
      return "card";
    } else {
      return "icon-pay_a";
    }
  },
  show1btn() {
    this.setData({
      show1: false,
    });
  },
  //抵扣选择响应
  discountHandle(e) {
    let bol = e.detail;
    let code = e.currentTarget.dataset.d.code;
    let index = e.currentTarget.dataset.index;

    console.log(this.data.order_data[0], this.data.order_data[0].order_deductions[index]);
    //处理选择
    this.screenDiscount(this.data.order_data[0], {
      checked: bol,
      code: code,
    });
    //重新计算
    this.preGoodsBuy(); //直接购买
  },
  //筛选抵扣
  screenDiscount(item, value) {
    this.deductionListHandle(item, value);
  },
  deductionListHandle(item, value) {
    let checkDeductionList = this.data.checkDeductionList;
    // let service_fee = this.data.service_fee;
    // let note = this.data.note;
    let isHasPreId = false;

    if (checkDeductionList.length > 0) {
      checkDeductionList.forEach((deduction, index) => {
        if (deduction && deduction.pre_id == item.pre_id) {
          isHasPreId = true;
          if (value && value.checked) {
            // 选中的时候检查是否有对应的code
            if (deduction.deduction_ids && deduction.deduction_ids.indexOf(value.code) == -1) {
              deduction.deduction_ids.push(value.code);
            }
          } else if (value && !value.checked) {
            // 取消选中的时候检查去掉对应的code
            if (deduction.deduction_ids && deduction.deduction_ids.indexOf(value.code) > -1) {
              deduction.deduction_ids.splice(deduction.deduction_ids.indexOf(value.code), 1);
            }
          }

          // 留言和安装选项重新赋值
          // deduction.note = note[item.pre_id];
          // deduction.service_fee = service_fee[item.pre_id];
        }
      });
    }
    if (!isHasPreId) {
      checkDeductionList.push({
        deduction_ids: value && value.code ? [value.code] : [],
        pre_id: item.pre_id,
      });
    }
    this.setData({ checkDeductionList });
    // console.log('checkDeductionList:', this.data.checkDeductionList)
  },
  //优惠券
  showCoupon() {
    if (this.data.coupon_size == 0) {
      wx.showToast({
        icon: "none",
        title: "暂无优惠券使用",
        duration: 1500,
      });
      return;
    }
    this.setData({
      popupCouponSpecs: true,
    });
  },
  //选择优惠券
  selectCoupon(e) {
    let couponBol = e.detail;
    let index = e.currentTarget.dataset.index;
    // let item = e.currentTarget.dataset.item;
    this.setData({
      ["coupons[" + index + "].checked"]: couponBol,
    });
    //处理选择
    //因为换了组件改调用方法
    this.screenCoupon(couponBol, this.data.coupons[index],e.type);
    //设置view
    this.setCouponView();
    //重新计算
    this.preGoodsBuy(); //直接购买
  },
  //筛选数据优惠券状态
  screenCoupon(couponBol , valObj, type) {
    let tarValue = valObj;
    let checkCouponList = this.data.checkCouponList;
    if (this.data.checkCouponList.length > 0) {
      for (let i = 0; i < this.data.checkCouponList.length; i++) {
        if (this.data.checkCouponList[i].id == tarValue.id) {
          checkCouponList.splice(i, 1);
        }
      }
    }
    if (this.data.is_coupon_SELE && type) {
      //开启折叠优惠券并且为点击复选框为选中状态
      this.data.coupons_temp[tarValue.coupon_id].num = couponBol ? 1 : 0;
      this.setData({
        coupons_temp: this.data.coupons_temp
      });
    }
    if (couponBol) {
      //选中添加
      checkCouponList.push(tarValue);
    } else {
      //取消选中
      this.setData({
        cup_notice: true
      });
    }
    this.setData({
      checkCouponList: checkCouponList
    });
  },
  //设置view
  setCouponView() {
    this.setData({
      use_coupon_size: this.data.checkCouponList.length,
    });
  },
  //关闭优惠卷
  couponclose() {
    this.setData({
      popupCouponSpecs: false,
    });
  },
  realnameinp(e) {
    let val = e.detail.value;
    this.setData({
      "form.realname": val,
    });
  },
  mobileinp(e) {
    let val = e.detail.value;
    this.setData({
      "form.mobile": val,
    });
  },
  agreementPayinp(e) {
    let bol = e.detail;
    this.setData({
      agreementPay: bol,
    });
  },
  showPay() {
    this.setData({
      agreementPayShow: true,
    });
  },

  //提交订单
  submit(btn) {
    let val = btn;
    let that = this;
    let urlStr = "";
    if (this.data.cashier_type == "hotel") {
      urlStr += app.getNetAddresss("plugin.hotel.frontend.Order.create");
      urlStr += "&price=" + this.data.payMuch;
      urlStr += "&hotel_id=" + this.data.hotel_id;
      urlStr += "&member_coupon_ids=";
      urlStr += "&orders=";
      urlStr += "&mobile=" + this.data.form.mobile;
      urlStr += "&realname=" + this.data.form.realname;
    } else if(this.data.cashier_type == "scanning_payment"){
      urlStr += app.getNetAddresss("plugin.sweep-buy.frontend.controllers.create.index");
      urlStr += "&price=" + this.data.payMuch;
      urlStr += "&goods_id=" + this.options.goods_id;
      urlStr += "&orders=" + JSON.stringify(this.assembleDeduction());
    } else {
      urlStr += app.getNetAddresss("plugin.store-cashier.frontend.Order.create");
      urlStr += "&price=" + this.data.payMuch;
      urlStr += "&store_id=" + this.data.store_id;
      urlStr += "&member_coupon_ids=" + JSON.stringify(this.assembleCoupons());
      urlStr += "&orders=" + JSON.stringify(this.assembleDeduction());
      urlStr += "&mobile=" + this.data.form.mobile;
      urlStr += "&realname=" + this.data.form.realname;
    }
    if (this.data.clicktag == 0) {
      this.setData({
        clicktag: 1,
      });
      if (this.data.agreementPayData) {
        if (!this.data.agreementPay) {
          this.setData({
            clicktag: 0,
          });
          wx.showToast({
            icon: "none",
            title: "请先勾选支付协议",
            duration: 1500,
          });
          return;
        }
      }

      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              order_ids: res.data.order_ids,
            });
            that.getMultipleOrderInfo(val);
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
            that.data.isPayClick = false;
          }
          setTimeout(function () {
            that.setData({
              clicktag: 0,
            });
          }, 1000);
        },
        fail: function (res) {
          console.log(res);
        },
      });
    }
  },
  //多订单合并支付获取信息接口方法
  getMultipleOrderInfo(val) {
    let urlStr = app.getNetAddresss("order.merge-pay");
    urlStr += "&order_ids=" + this.data.order_ids;
    urlStr += "&pid=" + this.data.uid;
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            order_sn: res.data.order_pay.pay_sn,
            balance: res.data.member.credit2,
            money: res.data.order_pay.amount,
            uid: res.data.order_pay.uid,
            order_pay_id: res.data.order_pay.id,
            buttons: res.data.buttons,
            min_redirect_url: res.data.min_redirect_url,
          });
          this.handlePay(val, val.value);
        } else {
          wx.showModal({
            title: "提示",
            content: res.msg,
            success(res) {
              if (res.confirm) {
                wx.reLaunch({
                  url: "/packageG/index/index",
                });
                console.log("用户点击确定");
              } else if (res.cancel) {
                console.log("用户点击取消");
              }
            },
          });
          this.data.isPayClick = false;
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getCenter() {
    let that = this;
    let urlStr = "";
    let json = {};
    console.log(this.data.store_id, "getCenter的store_id");
    if (this.data.cashier_type === "hotel") {
      json = {
        hotel_id: this.data.hotel_id,
      };
      urlStr = app.getNetAddresss("plugin.hotel.frontend.cashier.center.index");
    } else {
      json = {
        store_id: this.data.store_id,
      };
      urlStr = app.getNetAddresss("plugin.store-cashier.frontend.cashier.center.getPaySet");
    }
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (that.data.cashier_type === "hotel") {
            that.initStore(res.data.get_hotel_info);
          } else {
            that.initStore(res.data.get_store_info);
          }

          that.setData({
            agreementPayData: res.data.get_pay_protocol,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
});
